package server

import (
	"fmt"
	"gitee.com/zhongguo168a/go-nodex/nodex/server/message"
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"io"
)

type IMessage interface {
	PackageLen() int
	Pack(write io.Writer) error
	Unpack(reader io.Reader) error
}

func UnpackReceivedData(reader io.Reader, server IServer, msgHandler IMsgHandle, req *Request) (err error) {
	defer func() {
		if errRecover := recover(); errRecover != nil {
			err = errorx.New("UnpackReceivedData Panic")
		}
	}()
	msg := &message.RequestMessage{}
	if unpackerr := msg.Unpack(reader); unpackerr != nil {
		return errorx.Wrap(unpackerr, "unpack message")
	}
	req.Message = msg
	router := msgHandler.GetRoute(msg.Route)
	if router == nil {
		return errorx.New("router not found", datax.M{"Route": msg.Route})
	}
	req.Route = router
	// 处理参数
	args, newerr := router.NewArgs()
	if newerr != nil {
		return errorx.Wrap(newerr, "new args", datax.M{"Route": msg.Route})
	}
	req.Args = args

	if unpackerr := message.Unpack(msg.Data, msg.SerializeMode, req.Args); unpackerr != nil {
		return errorx.Wrap(unpackerr, fmt.Sprintf("unpack args"))
	}

	return nil
}
